package com.example.yimai.service.impl;

import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.yimai.entity.Order;
import com.example.yimai.mapper.OrderMapper;
import com.example.yimai.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AlipayService {

    public static final String WEB_URL = "http://localhost:8080";

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderMapper orderMapper;

    public String createAlipay(String orderId, String subject) {
        String verify = orderService.verify(orderId);
        if(!verify.equals("success")) throw new RuntimeException(verify);
        try {
            //初始化SDK
            AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

            //构建响应参数
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();

            request.setReturnUrl(WEB_URL + "/#/alipay/return");
            request.setNotifyUrl(WEB_URL + "/api/alipay/notify");

            // 获取订单信息：根据 serialNumber 查询
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("serialNumber", orderId);
            Order order = orderMapper.selectOne(queryWrapper);

            // 检查订单是否存在
            if (order == null) {
                throw new RuntimeException("订单不存在，无法创建支付宝支付");
            }

            model.setOutTradeNo(order.getSerialNumber());
            model.setTotalAmount(order.getCost().toString());
            model.setSubject(subject);
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            model.setTimeoutExpress("1m");

            request.setBizModel(model);

            return alipayClient.pageExecute(request).getBody();
        }catch (Exception e){
            throw new RuntimeException("支付宝创建订单失败: " + e.getMessage());
        }
    }

    public String refund(String orderId) {
        try {
            //初始化SDK
            AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());
            //构建请求参数
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            AlipayTradeRefundModel model = new AlipayTradeRefundModel();

            // 获取订单信息：根据 serialNumber 查询
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("serialNumber", orderId);
            Order order = orderMapper.selectOne(queryWrapper);

            // 检查订单是否存在
            if (order == null) {
                throw new RuntimeException("订单不存在，无法进行退款");
            }

            model.setOutTradeNo(order.getSerialNumber());
            model.setRefundAmount(order.getCost().toString());

            request.setBizModel(model);
            alipayClient.execute(request);
            return "success";
        }catch (Exception e){
            throw new RuntimeException("支付宝退款失败: " + e.getMessage());
        }
    }

    private static AlipayConfig getAlipayConfig() {
        String privateKey  = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCZASqLOEIFLQNtincvzAFusOevkhO2wHbVTMwU1IQ89Pa8MK4U8zMG5eLTNkgmOpMMcaLKsPfLOFsZ8EIIf2Jj+KItpmaxpMEaV0gF8+IT42s6YN/C/S4Js/NNV7xJyZZevlKC/6SMSvajYAobE2NlhFk01C3rMyupvOCZUp901YgnTPgGeU8WBowCoY0fcY8LbDraVOoHbnR04LMbJG1PCYXpwy8cMCxQfETKTpNDr6Iq4OdhzYOQy9rVeBLIPSQzpYp19hYjKPmgdfEGDmPVhfsurJ17fWJxB7KjBOUflwQR2Frd/NX01wxijVYVwQrXWZvDqkyWbSQxiFoNWbu/AgMBAAECggEAcqTvDdYfkeVClkeUOtovkJM5ZtKbtunLoNOkb081rr8WSbhoGAaKi3ahWQVpVku5dy+GfT3QzhLyICNoNxnLzYC1dGMku6LpliUkMGGnWqOi6uE/iMlQP7D4c1F0Ig3MgD03cjS/ROe+mngR2mvSpHRgqzb5GS0EYHDIEdpY5J8aMVf01gU5YJ7zBNbl+Jdf8afzQhxJYmvaH4oYJ36Ydl5gIlU76L/KXzTPFVnC5N/nCBYYqEV7HPGwg6qPaebtOz8FadHY6OXIlNZjvTRBgRHYFVJGXMqOzEKFE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sA1NaZ9wF6roP1dIAnQ8cP2yUhzI8WyHbhvOkDqVaQ/S9O96aW2OpQrBWkfaxOziNQhmP3ZVxvOpw3UsU2WwgE692ZrXc+7aPZ2DsIwGDptA1Cba0fbJfIdkrvl2p7m+OjgKYo3zrP2M1pUCMvqpcSbCKLE5+1mSRdaK2JYIBf20+E286Md00ChFoyzvczrRWm2s50stkPYD/DInD+2ROxVZJTAHv9pFhMEzxLcuglzkkgzj5+szHuDYUP24jJRJaOQIDAQAB";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        alipayConfig.setAppId("9021000152627330");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        return alipayConfig;
    }

}
